package com.wlstock.funi.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

public class HttpUtils {

	public static HashMap<String, String> initHeader(){
		HashMap<String, String> header = new HashMap<String, String>();
		header.put("Connection", "keep-alive");
		header.put("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
		header.put("Accept-Encoding", "gzip, deflate");
		header.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");
		return header;
	}
	
	
	public static List<NameValuePair> getParms(HashMap<String, String> parmHash){
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		for (Iterator<Entry<String, String>> iterator = parmHash.entrySet().iterator(); iterator.hasNext();) {
			Entry<String, String> entry = (Entry<String, String>) iterator.next();
			NameValuePair parm = new BasicNameValuePair(entry.getKey(),entry.getValue());
			params.add(parm);
		}
		return params;
	}
	
	public static String setCookie(HttpResponse httpResponse){
		Map<String, String> cookieMap = new HashMap<String, String>(64);
		
		Header[] headers = httpResponse.getHeaders("Set-Cookie");
		System.out.println("----setCookieStore" + headers.toString());
		if (headers == null || headers.length == 0 ) {
			System.out.println("----there are no cookies");
			return null;
		}
		String cookie = "";
		for (int i = 0; i < headers.length; i++) {
			cookie += headers[i].getValue();
			if (i != headers.length - 1) {
				cookie += ";";
			}
		}
		if (!cookie.contains("JSESSIONID=")) {
			return null;
		}
		String cookies[] = cookie.split(";");
		for (String c : cookies) {
			c = c.trim();
			if (cookieMap.containsKey(c.split("=")[0])) {
				cookieMap.remove(c.split("=")[0]);
			}
			cookieMap.put(
					c.split("=")[0],
					c.split("=").length == 1 ? ""
							: (c.split("=").length == 2 ? c.split("=")[1] : c
									.split("=", 2)[1]));
		}
		System.out.println("----setCookieStore success");
		String cookiesTmp = "";
		for (String key : cookieMap.keySet()) {
			cookiesTmp += key + "=" + cookieMap.get(key) + ";";
		}
		LogUtils.i("cookie:"+ cookiesTmp.substring(0, cookiesTmp.length() - 2));
		return cookiesTmp.substring(0, cookiesTmp.length() - 2);
	}

	
	public static String getUrl(String url ,HashMap<String, String> params) {
		Set<String> set = params.keySet();
		StringBuffer sb = new StringBuffer("?");
		for (String key : set) {
			String value = params.get(key);
			sb.append(key).append("=").append(value).append("&");
		}
		String requestUrl = url + sb.substring(0, sb.length()-1);
		return requestUrl;
	}
}
